package com.cutthroatcreations.woodenrailway;

import java.util.ArrayList;
import com.cutthroatcreations.woodenrailway.ImageHandler.ImageLoader;
import com.cutthroatcreations.woodenrailway.WoodenrailwayActivity.trainJson;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;

public class TrainListAdapter extends BaseAdapter {

	private static String TAG = "TrainListAdapter";
	private static LayoutInflater inflater = null;
	private Activity activity;
	public ImageLoader imageLoader;
	private ArrayList<Train> allItems;
	private ArrayList<Train> items;
	public ArrayList<Train> filtered;
	private Filter filter;
	private TrainListFragment tlf;
	private int index;
	ContentWorker cw;
	ImageView image;
	ImageView imageOwned;
	ImageView imageOwnedControl;
	int listOwned;
	int listOwnedControl;
	int listNotOwnedControl;

	@SuppressWarnings("unchecked")
	public TrainListAdapter(Activity a, TrainListFragment tlf,
			ArrayList<Train> items) {

		this.activity = a;
		this.tlf = tlf;
		this.allItems = items;
		this.filtered = items;
		this.items = (ArrayList<Train>) items.clone();
		listOwned = activity.getResources().getIdentifier("check_blue",
				"drawable", activity.getPackageName());
		listOwnedControl = activity.getResources().getIdentifier("minus_red",
				"drawable", activity.getPackageName());
		listNotOwnedControl = activity.getResources().getIdentifier(
				"plus_green", "drawable", activity.getPackageName());
		inflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.imageLoader = new ImageLoader(activity.getApplicationContext());
		this.filter = new TrainsNameFilter();

	}

	public ArrayList<Train> getTrains() {

		return this.filtered;
	}

	public int getCount() {
		return items.size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {

		View vi = convertView;
		if (convertView == null)
			vi = inflater.inflate(R.layout.item, null);

		Train train = filtered.get(position);
		TextView text = (TextView) vi.findViewById(R.id.text);
		Log.i(TAG, train.getName() + " at index " + String.valueOf(index));
		image = (ImageView) vi.findViewById(R.id.image);
		imageOwned = (ImageView) vi.findViewById(R.id.listOwnedImage);
		imageOwnedControl = (ImageView) vi.findViewById(R.id.listColMan);
		imageOwned.setImageResource(listOwned);
		imageOwnedControl.setImageResource(listOwnedControl);
		if (WoodenApplication.getYearIndex() == 0) {
			imageOwned.setImageBitmap(null);
			imageOwnedControl.setImageBitmap(null);
		} else {

			cw = new ContentWorker(activity.getBaseContext(), train,
					WoodenApplication.cYears[WoodenApplication.getYearIndex()]);
			if (!cw.isOwned()) {
				imageOwned.setImageBitmap(null);
				imageOwnedControl.setImageResource(listNotOwnedControl);
			}
		}
		text.setText(train.getName());
		String imgName = train.getImageName().replace(")", "_");
		imgName = imgName.replace(" ", "%20");

		String imgUrl = CustomHttpClient.BASE_URL
				+ "image.php?width=50&height=50&image=img/" + train.getID()
				+ "/" + imgName;

		imageLoader.DisplayImage(imgUrl, image);
		imageOwnedControl.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				Train tr = filtered.get(position);

				ContentWorker cwClicked = new ContentWorker(activity
						.getBaseContext(), tr,
						WoodenApplication.cYears[WoodenApplication
								.getYearIndex()]);

				int result = cwClicked.checked();

				if (result > -1) {
					if (result > 0) {

						imageOwnedControl.setImageResource(listNotOwnedControl);
						imageOwned.setImageBitmap(null);

					} else {

						imageOwnedControl.setImageResource(listOwnedControl);
						imageOwned.setImageResource(listOwned);

					}
					updateOwned();
					notifyDataSetChanged();
				}

			}
		});
		return vi;
	}

	public void updateOwned() {
		tlf.onUpdateListener.updateTextView(WoodenApplication.getYearIndex());
	}

	public Filter getFilter() {
		if (filter == null)
			filter = new TrainsNameFilter();
		return filter;
	}

	private class TrainsNameFilter extends Filter {

		@Override
		protected FilterResults performFiltering(CharSequence constraint) {
			// NOTE: this function is *always* called from a background thread,
			// and
			// not the UI thread.
			constraint = constraint.toString().toLowerCase();
			FilterResults result = new FilterResults();
			if (constraint == null || constraint.toString().length() == 0) {
				result.count = allItems.size();
				result.values = allItems;
				return result;
			}
			if (constraint != null && constraint.toString().length() > 0) {
				ArrayList<Train> filt = new ArrayList<Train>();
				ArrayList<Train> lItems = new ArrayList<Train>();
				synchronized (this) {
					lItems.addAll(items);
				}
				for (int i = 0, l = lItems.size(); i < l; i++) {
					Train t = lItems.get(i);
					if (t.getName().toLowerCase().contains(constraint)) {
						filt.add(t);
					}
				}
				result.count = filt.size();
				result.values = filt;
			} else {

				synchronized (this) {
					result.values = items;
					result.count = items.size();
				}
			}
			return result;
		}

		@SuppressWarnings("unchecked")
		@Override
		protected void publishResults(CharSequence constraint,
				FilterResults results) {
			// NOTE: this function is *always* called from the UI thread.
			filtered = (ArrayList<Train>) results.values;
			tlf.setTrains(filtered);
			notifyDataSetChanged();

			items.clear();
			for (int i = 0, l = filtered.size(); i < l; i++)
				items.add(filtered.get(i));
			notifyDataSetInvalidated();
		}

	}
}